{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.good-name, .good-price {line-height: 34px;}
	.layui-form-item .layui-input-inline.end-time{float: none;}
	.layui-table-body{max-height: 480px !important;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
</style>
{/block}
{block name="main"}
<div class="layui-form ns-form">

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
		<div class="layui-inline">
			<div class="layui-input-inline">
				<input type="text" id="start_time" name="start_time" lay-verify="required" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
			<span class="layui-form-mid">-</span>
			<div class="layui-input-inline end-time">
				<input type="text" id="end_time" name="end_time" lay-verify="required|time" class="layui-input ns-len-mid" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
		</div>
	</div>

	<div class="layui-form-item goods_list">
		<label class="layui-form-label">活动商品：</label>
		<div class="layui-input-block">
			<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
			<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
		</div>
	</div>

	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
	<input type="hidden" name="goods_ids" value="" />
</div>
{/block}
{block name="script"}
<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="group-price">团购价</button>
	<button class="layui-btn layui-btn-primary" lay-event="purchase-num">最低购买数量</button>
</script>
<script>
	var goodsId = [], selectedGoodsId = [], goods_list = [];
    layui.use(['form', 'laydate'], function() {
        var form = layui.form,
            laydate = layui.laydate,
            repeat_flag = false,
            currentDate = new Date(),
            minDate = "";
        currentDate.setDate(currentDate.getDate() + 30);
		form.render();

		renderTable(goods_list); // 初始化表格

        //开始时间
        laydate.render({
            elem: '#start_time', //指定元素
            type: 'datetime',
            value: new Date(),
            done: function(value) {
                minDate = value;
                reRender();
            }
        });

        //结束时间
        laydate.render({
            elem: '#end_time', //指定元素
            type: 'datetime',
            value: new Date(currentDate)
        });

        /**
         * 重新渲染结束时间
         * */
        function reRender() {
            $("#end_time").remove();
            $(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class="layui-input ns-len-mid" autocomplete="off" readonly> ');
            laydate.render({
                elem: '#end_time',
                type: 'datetime',
                min: minDate
            });
        }

        /**
         * 表单验证
         */
        form.verify({
            time: function(value) {
                var now_time = (new Date()).getTime();
                var start_time = (new Date($("#start_time").val())).getTime();
                var end_time = (new Date(value)).getTime();
                if (now_time > end_time) {
                    return '结束时间不能小于当前时间!'
                }
                if (start_time > end_time) {
                    return '结束时间不能小于开始时间!';
                }
            },
            flnum: function(value) {
                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return '保留小数点后两位！'
                }
                if (Number(value) < 0){
                    return '价格不能小于0！';
				}
            },
			buy_num: function(value,item) {
				var stock = $(item).parents("tr").find(".stock").text();
                if (Number(value) < 2) {
                    return '最低购买数量不能小于2！'
                }
				if (Number(value) > stock) {
					return '购买数量不能大于库存数！'
				}
            },
			group_price: function(value, item) {
				var price = $(item).parents("tr").find(".goods-price").text();
				if (parseFloat(value) > parseFloat(price)) {
					return '团购价格不能大于商品价格';
				}
				if (value.trim() == "") {
					return '团购价格不能为空';
				}
				if (parseFloat(value) <= 0) {
					return '团购价格必须大于0';
				}
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '团购价格最多保留两位小数';
				}
			},
        });

        /**
         * 表单提交
         */
        form.on('submit(save)', function(data){
			if (!goodsId.length) {
				layer.msg("请选择活动商品！", {icon: 5, anim: 6});
				return;
			}
			data.field.goods_ids = goodsId;

			var goodsListArr = [];
			goods_list.forEach(function(item,index) {
				var goods_detail = {};
				goods_detail.sku_id = item.sku_id;
				goods_detail.goods_image = item.goods_image;
				goods_detail.goods_id = item.goods_id;
				goods_detail.groupbuy_price = item.groupbuy_price || 0;
				goods_detail.buy_num = item.buy_num || 0;
				goodsListArr.push(goods_detail);
			});
			data.field.goods_list = goodsListArr;

            if(repeat_flag) return;
            repeat_flag = true;

            $.ajax({
                type: 'POST',
                dataType: 'JSON',
                url: ns.url("groupbuy://shop/groupbuy/add"),
                data: data.field,
                async: false,
                success: function(res){
                    repeat_flag = false;

                    if (res.code == 0) {
                        layer.confirm('添加成功', {
                            title:'操作提示',
                            btn: ['返回列表', '继续添加'],
							closeBtn: 0,
                            yes: function(){
                                location.href = ns.url("groupbuy://shop/groupbuy/lists");
                            },
                            btn2: function() {
                                location.href = ns.url("groupbuy://shop/groupbuy/add");
                            }
                        });
                    }else{
                        layer.msg(res.message);
                    }
                }
            })
        });
    });

	// 表格渲染
	function renderTable(goods_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page: false,
			limit: Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					title: '商品名称',
					width: '26%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.goods_image ? ns.img(data.goods_image.split(",")[0],'small') : ''}" alt="">
								</div>
								<p class="ns-multi-line-hiding goods-name" data-goods_id="${data.goods_id}" title="${data.goods_name}">${data.goods_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					align: 'right',
					width: '15%',
					templet: function(data) {
						return '<p class="ns-line-hiding" title="'+ data.price +'">￥<span class="goods-price">' + data.price +'</span></p>';
					}
				}, {
					field: 'goods_stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.goods_stock +'</p>';
					}
				}, {
					title: '团购价(元)',
					unresize: 'false',
					width: '13%',
					templet: '#groupbuy_price'
				}, {
					title: '最低购买数量',
					unresize: 'false',
					width: '13%',
					templet: '#buy_num'
				}, {
					title: '操作',
					toolbar: '#operation',
					width: '10%',
					unresize: 'false'
				}]
			],
			data: goods_list,
			toolbar: '#toolbarOperation'
		});

		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "group-price":
					editInput(0,obj);
					break;
				case "purchase-num":
					editInput(1,obj);
					break;
			}
		});
	}

	function editInput(textIndex=0,data) {
		var text = [{
			name: '团购价',
			value: 'groupbuy_price'
		},{
			name: '最低购买数量',
			value: 'buy_num'
		}];

		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid" placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					goods_list.forEach(function (skuItem,skuIndex) {
						if (item.goods_id == skuItem.goods_id){
							goods_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				renderTable(goods_list);
				layer.closeAll();
			}
		});
	}

	/**
	 * 添加商品
	 */
	function addGoods(){
		goodsSelect(function(res) {
			if (!res.length) return false;

			for(var i=0;i<res.length;i++) {
				goodsId.push(res[i].goods_id);
				res[i].buy_num = 2;
				goods_list.push(res[i]);
			}
			renderTable(goods_list);
			$("input[name='goods_ids']").val(JSON.stringify(goodsId));

			selectedGoodsId = goodsId.toString();
		}, selectedGoodsId);
	}

	function delRow(obj,id) {
		for (var i = 0; i < goods_list.length; i++){
			if (goods_list[i].goods_id == parseInt(id)){
				goods_list.splice(i,1);
			}
		}

		if(goodsId.indexOf(id) != -1) goodsId.splice(goodsId.indexOf(id),1);
		selectedGoodsId = goodsId.toString();
		$(obj).parents("tr").remove();
	}

	function groupbuyPrice(index,event) {
		for (var i = 0; i < goods_list.length; i++){
			if (goods_list[i].goods_id == index)
				goods_list[i].groupbuy_price = event.srcElement.value;
		}
	}
	function groupbuyBuyNum(index,event) {
		for (var i = 0; i < goods_list.length; i++){
			if (goods_list[i].goods_id == index) goods_list[i].buy_num = event.srcElement.value;
		}
	}

    function back() {
        location.href = ns.url("groupbuy://shop/groupbuy/lists");
    }
</script>

<script type="text/html" id="groupbuy_price">
	<input type="number" class="layui-input ns-len-input groupbuy-price" value="{{d.groupbuy_price ? d.groupbuy_price : ''}}" lay-verify="group_price" min="0.00" oninput="groupbuyPrice({{ d.goods_id }},event)" onporpertychange="groupbuyPrice({{ d.goods_id }},event)"/>
</script>

<script type="text/html" id="buy_num">
	<input type="number" class="layui-input ns-len-input buy-num" value="{{d.buy_num ? d.buy_num : 2}}" lay-verify="buy_num" min="0.00" oninput="groupbuyBuyNum({{ d.goods_id }},event)" onporpertychange="groupbuyBuyNum({{ d.goods_id }},event)"/>
</script>

<script type="text/html" id="operation">
	<div class="ns-table-btn">
		<a class="layui-btn" onclick="delRow(this,{{d.goods_id}})">删除</a>
	</div>
</script>
{/block}